package JZ_Offer.algorithm.search;

/**
 * 二维数组中的查找
 *
 * @Author piper
 * @Date 2019/11/4 2:59 下午
 */
public class JZ4_二维数组中的查找 {

    /**
     * 暴力法 遍历
     *
     * @param target
     * @param array
     * @return
     */
    private static boolean find(int target, int[][] array) {
        if (array.length == 0) return false;
        if (array[0].length == 0) return false;

        for (int i = 0; i < array.length; i++) {
            int[] ints = array[i];
            for (int j = 0; j < ints.length; j++) {
                if (ints[j] == target) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 二分查找法
     *
     * @param target
     * @param array
     * @return
     */
    private static boolean find2(int target, int[][] array) {
        if (array.length == 0) return false;
        if (array[0].length == 0) return false;

        for (int i = 0; i < array.length; i++) {
            int[] ints = array[i];
            if (ints[0] <= target && ints[ints.length - 1] >= target) {
                int l = 0, r = ints.length - 1, m = 0;
                while (l <= r) {
                    m = (r + l) / 2;
                    if (ints[m] < target) {
                        l = m + 1;
                    } else if (ints[m] > target) {
                        r = m - 1;
                    } else {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    public static void main(String[] args) {
        int[][] array = {{1, 2, 8, 9}, {2, 4, 9, 12}, {4, 7, 10, 13}, {6, 8, 11, 15}};
        System.out.println(find2(1, array));
    }
}
